package cn.edu.laud.sany.dataimport;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLTransientConnectionException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.cassandra.thrift.TimedOutException;

import cn.edu.laud.sany.types.RowData;
import cn.edu.laud.sany.utils.ProcessManager;

public class LaUDRunner_JDBC extends LaUDRunner
{
	public static int JDBC_BATCH_SIZE = 10000;
	protected Statement laudStatement;
	private Connection laudConnection;
	List<String> sqls = new ArrayList<String>();
	
	public LaUDRunner_JDBC(int no, String keyspace)
	{
		super(no, keyspace);
	}
	
	@Override
	public boolean openConnection()
	{
		try
		{
			String jdbcString = LaUDImport.host[threadNum % LaUDImport.host.length];
			try
			{
				logger.info("try get jdbc connection...");
				laudConnection = DriverManager.getConnection(jdbcString, "", "");
				laudStatement = laudConnection.createStatement();
				logger.info("get jdbc connection successful.");
			}
			catch (SQLException e1)
			{
				e1.printStackTrace();
				logger.error("get jdbc connection error:" + e1.getMessage() + ", jdbc url:"
						+ jdbcString);
				return false;
			}
			laudStatement.execute("use " + keyspace);
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
			logger.error(e1.getMessage());
			return false;
		}
		return true;
	}
	
	@Override
	public void closeConnection()
	{
		try
		{
			if (laudStatement != null)
			{
				try
				{
					laudStatement.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
					logger.error(e.getMessage());
				}
			}
			if (laudConnection != null)
			{
				try
				{
					laudConnection.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
					logger.error(e.getMessage());
				}
			}
			logger.info("laud connect closed successfully.");
		}
		catch (Exception e)
		{
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	@Override
	public void endImport() throws IOException
	{
		int sqlNum = sqls.size();
		if (sqlNum > 0)
		{
			boolean importSucceed = executeSQL(sqls);
			sqls.clear();
			if (importSucceed == false)
			{
				nowLineNum = nowLineNum - sqlNum;
			}
		}
	}
	
	@Override
	public void addRowData(RowData rowData) throws IOException
	{
		sqls.add(String.format(LaUDImport.cQLInsertFormat, rowData.paraId, rowData.localTime,
				rowData.equipCode, rowData.paravalue));
		int sqlNum = sqls.size();
		if (sqlNum == JDBC_BATCH_SIZE)
		{
			while (executeSQL(sqls) == false)
			{
				logger.info("execute [" + sqlNum + "] sqls error, will try again.");
				try
				{
					Thread.sleep(100);
				}
				catch (InterruptedException e)
				{
				}
			}
			ProcessManager.addRealImportCount(sqlNum);
			sqls.clear();
		}
	}
	
	protected boolean executeSQL(List<String> sqls)
	{
		int timeouttime = 5;
		while (timeouttime > 0)
		{
			StringBuilder sb = new StringBuilder(2000);
			sb.append("BEGIN BATCH USING CONSISTENCY ");
			sb.append(LaUDImport.cQLTranscation);
			sb.append(" ");
			for (String sql : sqls)
			{
				sb.append(sql);
				sb.append(" ");
			}
			sb.append(" APPLY BATCH");
			try
			{
				laudStatement.execute(sb.toString());
				sqls.clear();
				return true;
			}
			catch (SQLException e)
			{
				logger.equals(e.getMessage());
				if (timeouttime > 0 && (e.getCause() instanceof TimedOutException))
				{
					logger.warn("time out exception, will try again after 5 secondes,[time "
							+ timeouttime + "]");
					timeouttime--;
					try
					{
						Thread.sleep(5000);
					}
					catch (InterruptedException e1)
					{
						logger.equals(e.getMessage());
					}
				}
				else if (timeouttime > 0
						&& (e.getCause() instanceof SQLTransientConnectionException))
				{
					logger.warn(e.getMessage() + ", will try again after 5 secondes,[time "
							+ timeouttime + "]");
					timeouttime--;
					try
					{
						Thread.sleep(5000);
					}
					catch (InterruptedException e1)
					{
						logger.equals(e.getMessage());
					}
				}
				else
				{
					logger.error(e.getMessage() + "(sql:" + sb.toString().substring(0, 100)
							+ "...)");
					return false;
				}
			}
		}
		return false;
	}
	
}
